#include <iostream>
#include <complex>
#include <cmath>
#include <vector>

#define MAX_ERROR 0.01
const std::complex<double> J(0, 1);
//

#define A2P(angle) (3.1415926 * (angle) / 180)
int main()
{
    // beta2=abs(acos((1-S(1,1)*S(2,2)+S(2,1)*S(1,2))/(2*S(S,1))))/pi
    // 固定住 Z1 Z2
    double Z1 = 38;
    double Z2 = 45;
    // 目标量 fa1 fa2
    double f0 = 1;
    double fa1 = 2.4;
    double fa2 = 5.2;
    // 扫描量 E1 E2
    double E1LEFT = 0.01;
    double E1RIGHT = 75;
    double E2LEFT = 0.01;
    double E2RIGHT = 75;

    double E1TmpFa1 = 0;
    double E2TmpFa1 = 0;
    double E1TmpFa2 = 0;
    double E2TmpFa2 = 0;

    double FlagFa1 = 0;
    double FlagFa2 = 0;

    int FinalFlag = 0;
    double FineE1 = 0;
    double FineE2 = 0;
    double FineELInTry = 0;
    double FineZLInTry = 0;
    double LargestDistance = 99999;
    double LargestDistanceTry = 99999;
    // 扫描 EL ES 固定ZS
    for (double E1 = E1LEFT; E1 <= E1RIGHT; E1 += 0.01)
    {
        for (double E2 = E2LEFT; E2 <= E2RIGHT; E2 += 0.01)
        {
            E1TmpFa1 = A2P(E1) * fa1 / f0;
            E2TmpFa1 = A2P(E2) * fa1 / f0;
            E1TmpFa2 = A2P(E1) * fa2 / f0;
            E2TmpFa2 = A2P(E2) * fa2 / f0;

            // std::complex<double> fa1Tmp = 2 * Z2 * tan(E2TmpFa1) - Z1 * tan(E1TmpFa1);
            std::complex<double> fa1Tmp = (cos(E1TmpFa1) * (2 * Z2 * cos(E1TmpFa1) * cos(E2TmpFa1) - Z1 * sin(E1TmpFa1) * sin(E2TmpFa1))) / (Z2 * cos(E2TmpFa1));
            // std::complex<double> fa2Tmp = 2 * Z2 * tan(E2TmpFa2) - Z1 * tan(E1TmpFa2);
            std::complex<double> fa2Tmp = (cos(E1TmpFa2) * (2 * Z2 * cos(E1TmpFa2) * cos(E2TmpFa2) - Z1 * sin(E1TmpFa2) * sin(E2TmpFa2))) / (Z2 * cos(E2TmpFa2));

            FlagFa1 = abs(fa1Tmp);
            FlagFa2 = abs(fa2Tmp);
            if ((FlagFa1 < MAX_ERROR) && (FlagFa2 < MAX_ERROR))
            {
                FinalFlag = 1;
                // 综合距离最小的解
                if (FlagFa1 + FlagFa2 < LargestDistance)
                {
                    LargestDistance = FlagFa1 + FlagFa2;
                    FineE1 = E1;
                    FineE2 = E2;
                }
                // 找到解
                if(E1 < E2)
                {
                    printf("解: E1 = %lf, E2 = %lf, 差距 = %lf\n", E1, E2, FlagFa1 + FlagFa2);
                }
            }
            else
            {
                if (FlagFa1 + FlagFa2 < LargestDistanceTry)
                {
                    FineELInTry = E1;
                    FineZLInTry = E2;
                    LargestDistanceTry = FlagFa1 + FlagFa2;
                }
            }
        }
    }
    if (FinalFlag != 0)
    {
        printf("综合最好解: E1 = %lf, E2 = %lf 差距: %lf\n", FineE1, FineE2, LargestDistance);
    }
    else
    {
        printf("最收敛尝试: E1 = %lf, E2 = %lf 差距: %lf\n", FineELInTry, FineZLInTry, LargestDistanceTry);
    }
    return 0;
}

